package com.yuda.operationcenter.controller;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.io.IOException;
import java.util.Set;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.yuda.common.core.utils.file.OssFileUtils;
import com.yuda.operationcenter.domain.OperBanner;
import com.yuda.operationcenter.service.IOperBannerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.yuda.common.log.annotation.Log;
import com.yuda.common.log.enums.BusinessType;
import com.yuda.common.security.annotation.PreAuthorize;
import com.yuda.operationcenter.domain.OperInformation;
import com.yuda.operationcenter.service.IOperInformationService;
import com.yuda.common.core.web.controller.BaseController;
import com.yuda.common.core.web.domain.AjaxResult;
import com.yuda.common.core.utils.poi.ExcelUtil;
import com.yuda.common.core.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 资讯Controller
 *
 * @author wyn
 * @date 2021-04-12
 */
@RestController
@RequestMapping("/information")
public class OperInformationController extends BaseController {
    @Autowired
    private IOperInformationService operInformationService;

    @Autowired
    private IOperBannerService operBannerService;

    @Autowired
    private OSS ossClient;

    @Autowired
    private RedisTemplate<String, String> redisTemplateDB1;

    /**
     * 查询资讯列表
     */
    @PreAuthorize(hasPermi = "gwoper:news:list")
    @GetMapping("/list")
    public TableDataInfo list(OperInformation operInformation) {
        startPage();
        List<OperInformation> list = operInformationService.selectOperInformationList(operInformation);
        return getDataTable(list);
    }

    /**
     * 导出资讯列表
     */
    @PreAuthorize(hasPermi = "gwoper:news:export")
    @Log(title = "资讯", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, OperInformation operInformation) throws IOException {
        List<OperInformation> list = operInformationService.selectOperInformationList(operInformation);
        ExcelUtil<OperInformation> util = new ExcelUtil<OperInformation>(OperInformation.class);
        util.exportExcel(response, list, "information");
    }

    /**
     * 获取资讯详细信息
     */
    @PreAuthorize(hasPermi = "gwoper:news:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(operInformationService.selectOperInformationById(id));
    }

    /**
     * 新增资讯
     */
    @PreAuthorize(hasPermi = "gwoper:news:add")
    @Log(title = "资讯", businessType = BusinessType.INSERT)
    @PostMapping
    public synchronized AjaxResult add(@RequestBody OperInformation operInformation) {
        if (operInformation.getId() == null) {
            int i = operInformationService.insertOperInformation(operInformation);
            if (i > 0) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id", operInformation.getId());
                return AjaxResult.success(jsonObject);
            }
            return AjaxResult.error();
        }

        return edit(operInformation);
    }

    /**
     * 修改资讯
     */
    @PreAuthorize(hasPermi = "gwoper:news:edit")
    @Log(title = "资讯", businessType = BusinessType.UPDATE)
    @PutMapping
        public synchronized AjaxResult edit(@RequestBody OperInformation operInformation) {

        if (operInformation.getOnSell() == 1) {
            Integer orderNo = operInformation.getOrderNo();
            //判断orderNo是否存在，如果不存在，则直接更新为此数字
            boolean exist = operInformationService.existOrder(orderNo);

            if (!exist) {
//                return toAjax(operInformationService.updateOrderNo(operInformation.getId(), orderNo));
                return toAjax(operInformationService.updateOperInformation(operInformation));
            }

            //根据id查询以前的order
            OperInformation operInformation1 = operInformationService.selectOne(operInformation.getId());
            //如果存在，走下边的流程
            setOrderNo(operInformation.getOrderNo(), operInformation1.getOrderNo());
            //置位空，因为setOrderNo的时候已经完成了 设置值的工作
            operInformation.setOrderNo(null);
        }
        return toAjax(operInformationService.updateOperInformation(operInformation));
    }


    /**
     * 删除资讯
     * @return
     */
    @PreAuthorize(hasPermi = "gwoper:news:remove")
    @Log(title = "资讯", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {

        //如果该咨询已绑定banner图，则不允许删除该咨询

        //将long数组转成String类型
        List<String> list = new ArrayList<>();
        for (int i = 0; i < ids.length; i++) {
            String s = String.valueOf(ids[i]);
            list.add(s);
        }
        String[] sum = new String[list.size()];
        list.toArray(sum);

        //查出所有banner图
        List<OperBanner> list2 = operBannerService.selectByInnerLineUrl(sum);

        //若list2为空，说明没绑定banner图，直接删除选中的咨询。
        if (list2.isEmpty()) {

            return toAjax(operInformationService.deleteOperInformationByIds(ids));
        }

        else {
            Set<String> set = new HashSet<>();//已绑定的内链地址
            for (OperBanner operBanner : list2) {
                set.add(operBanner.getInnerLineUrl());
            }
            return AjaxResult.error("以下id的咨询已绑定banner，不可删除" + set);

        }
    }

    @PreAuthorize(hasPermi = "gwoper:news:remove")
    @Log(title = "删除图片", businessType = BusinessType.DELETE)
    @DeleteMapping("/rmCover/{id}")
    public AjaxResult removeImage(@PathVariable Long id) {
        return toAjax(operInformationService.removeImage(id));
    }


    @Log(title = "上传图片", businessType = BusinessType.UPDATE)
    @PostMapping("/uploadImageForWangEditor")
    public String uploadImageForWangEditor(MultipartFile[] multipartFile) {

        //获取文件的后缀名称
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("errno", 0);
        JSONArray jsonArray = new JSONArray();
        for (MultipartFile file : multipartFile) {
            String fileName = OssFileUtils.generateFileName(file);

            try {
                ossClient.putObject("operationcenter", fileName, new ByteArrayInputStream(file.getBytes()));
                String url = "http://operationcenter.oss-cn-beijing.aliyuncs.com" + "/" + fileName;

                JSONObject jo = new JSONObject();
                jo.put("url", url);
                jo.put("alt", "");
                jo.put("href", "");
                jsonArray.add(jo);

            } catch (IOException e) {
                jsonObject.put("errno", 1);
                e.printStackTrace();
            }
        }
        jsonObject.put("data", jsonArray);
        return jsonObject.toJSONString();
    }


    //交换排序值
    @PreAuthorize(hasPermi = "gwoper:news:replace")
    @PutMapping("/replaceOrder/{order1}/{order2}")
    public AjaxResult replaceOrderNoByOrder(@PathVariable int order1, @PathVariable int order2) {

        long id1, id2;
        int res1 = 0;
        OperInformation operInformation1 = operInformationService.selectedByOrderAndSellEq1(order1);

        if (operInformation1 != null && operInformation1.getOnSell() == 1) {

            //判断orderNo是否存在，如果不存在，则直接更新为此数字
            boolean exist = operInformationService.existOrder(order2);

            if (!exist) {
                return toAjax(operInformationService.updateOrderNo(operInformation1.getId(), order2));
            }

            OperInformation operInformation2 = operInformationService.selectedByOrderAndSellEq1(order2);
            id1 = operInformation1.getId();
            id2 = operInformation2.getId();
            res1 = operInformationService.updateOrderNo(id1, order2, id2, order1);
        }
        if (res1 == 1)
            return AjaxResult.success();
        return AjaxResult.error();
    }


    /**
     * 把小 的oder 以下的 递增，留好位置
     *
     * @param order1
     * @param order2
     * @return
     */
//    @PreAuthorize(hasPermi = "gwoper:news:edit")
//    @PutMapping("/setOrder/{order1}/{order2}")
    private AjaxResult setOrderNo(int order1, int order2) {

        //1。把大于等于该值的order都+1
        return toAjax(operInformationService.orderAddOne(Math.min(order1, order2), Math.max(order1, order2)));
    }


    /**
     * 批量上下架
     *
     * @param on_sell 0下架 1上架 2待上架
     */
    @PreAuthorize(hasPermi = "gwoper:news:publishout")
    @Log(title = "批量更新", businessType = BusinessType.UPDATE)
    @PutMapping("/{ids}/{on_sell}")
    public synchronized AjaxResult batchUpdateSellStatus(@PathVariable Long[] ids, @PathVariable int on_sell) {
        //检查能否上架
        List<Long> longs = new ArrayList<>();
        if (on_sell == 1) { //上架
            for (Long id : ids) {

                int i = operInformationService.checkIsCanUpdateStatus(id);
                if (i == 0) {
                    longs.add(id);
                } else {
                    return new AjaxResult(400, id + "号图文咨询信息不全，不可上架！");
                }
            }
            //获取全部图文的最大排序值
            for (Long id : ids) {
                int MaxOrderNo = operInformationService.MaxOrderNo();
                operInformationService.batchUpdateSellStatus(id, on_sell, MaxOrderNo + 1);
            }
        }

        redisTemplateDB1.delete("yd_ks:web_static:cloud:information");
        redisTemplateDB1.delete("yd_ks:web_static:cloud:information_info");

        return toAjax(operInformationService.batchUpdateSellStatus(ids, on_sell));
    }
}




/*
 *//**
 * 批量上下架
 *
 * @param on_sell 0下架 1上架 2待上架
 *//*
    @PreAuthorize(hasPermi = "gwoper:news:publishout")
    @Log(title = "批量更新" , businessType = BusinessType.UPDATE)
    @PutMapping("/{ids}/{on_sell}")
    public AjaxResult batchUpdateSellStatus(@PathVariable Long[] ids, @PathVariable int on_sell) {


        //获取全部order_no不为0的对象
        List<OperInformation> list01 =  operInformationService.selectOperInformation_OrderNo_Notnull();
        //获取order字段的值
        List order_no_Notnull = new ArrayList();
        for(int i=0;i<list01.size();i++){
            order_no_Notnull.add(list01.get(i).getOrderNo());
        }
        //获取全部图文的最大排序值
        int MaxOrderNo = operInformationService.MaxOrderNo().getOrderNo();
        //获取选中的图文；
        List<OperInformation> selected = operInformationService.selectd(ids);
        //获取未选中的上架中的图文集合，更新排序值
        List<OperInformation> unSelected = operInformationService.UnSelected(ids);




        //检查能否上架
        List<Long> longs = new ArrayList<>();
        if (on_sell == 1) { //上架
            for (Long id : ids) {

                int i = operInformationService.checkIsCanUpdateStatus(id);
                if (i == 0) {
                    longs.add(id);
                }
                else {
                    return new AjaxResult(400, id + "号图文咨询信息不全，不可上架！");
                }
            }

            //on_sell其他状态==>上架状态，上架之前为之设置排序值：默认递增
            //获取选中咨询图文order_no为0的对象
            List<OperInformation> list02 =  operInformationService.selectOperInformation_OrderNo_null(ids);
            //新上架的默认为之排序
            for(int i=0;i<list02.size();i++){

                long id = list02.get(i).getId();
                int orderNo = list02.get(i).getOrderNo();
                orderNo = (MaxOrderNo + i + 1); //全部图文的最大排序值
                operInformationService.updateOrderNo(id,orderNo);//根据id更新批量传入准备上架的咨询
            }

            Long[] longs1 = new Long[longs.size()];
            return toAjax(operInformationService.batchUpdateSellStatus(longs.toArray(longs1), on_sell));

        }

        else {
            //若是待上架、下架，则把order_no字段变为：0

            System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
            System.out.println("选中的上架中的图文个数:" + selected.size());
            System.out.println("未选中的上架中的图文个数:" + unSelected.size());
            System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");

            int SumOnSell = 0;
            for (int i = 0; i < selected.size(); i++) {
                SumOnSell = SumOnSell+selected.get(i).getOnSell();
            }

            System.out.println("---------------------------------------");
            System.out.println("选中图文的on_sell字段和："+SumOnSell);
            System.out.println("选中图文的集合长度："+selected.size());
            System.out.println("---------------------------------------");



            //如果选中的图文on_sell字段都为：1，则和等于集合的长度。
            // 上架状态==>其他状态，需要将未选中的排序值重新排序，然后选中的图文将排序值改为：0
            if (SumOnSell == selected.size()) {


                System.out.println("*************************");
                System.out.println(unSelected.size());
                System.out.println(selected.size());
                System.out.println("*************************");


                //更新未选中的图文排序值大于选中图文排序值的图文，使排序值连续
                for (int i = 0; i < unSelected.size(); i++) {
                    for (int j = 0; j < selected.size(); j++) {
                        if (unSelected.get(i).getOrderNo() > selected.get(j).getOrderNo()) {
                            long id = unSelected.get(i).getId();
                            int NewOrder = unSelected.get(i).getOrderNo() - 1;
                            operInformationService.updateUnSelectedOrderNo(id, NewOrder);
                        }
                    }
                }

                //将order_no字段变为：0
                for (OperInformation operInformation : selected) {

                    System.out.println("---------------------");
                    System.out.println(operInformation);
                    System.out.println("---------------------");

                    operInformationService.updateOrder(operInformation.getId());
                }
            }
            else{
                //on_sell其他状态==>其他状态，只需要将order_no字段变为：0
                for (OperInformation operInformation : selected) {

                    System.out.println("---------------------");
                    System.out.println(operInformation);
                    System.out.println("---------------------");

                    operInformationService.updateOrder(operInformation.getId());//将order_no字段变为：0
                }

            }
        }
        return toAjax(operInformationService.batchUpdateSellStatus(ids, on_sell));
    }
}*/
